package servlet;

import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


@WebServlet(urlPatterns = {"/user"})
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //jdbc操作数据库
            List<User> users = new ArrayList<>();
            //1.加载驱动
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");

                //2.获取连接(url,password,username)
                String url="jdbc:mysql://127.0.0.1:3306/jdbc?charactern=UTF-8";
                try {
                    Connection connection = DriverManager.getConnection(url, "root", "123456");
               /* if (connection!=null){
                    System.out.println("连接成功");
                }*/
                    String sql="select * from user";

                    //4.预编译sql
                    PreparedStatement prepareStatement = connection.prepareStatement(sql);

                    //5.有参数设置参数

                    //6.执行sql
                    ResultSet resultSet = prepareStatement.executeQuery();
                    //7.遍历结果集
                    while (resultSet.next()){
                        User user = new User();
                        user.setId(resultSet.getInt(1));
                        user.setName(resultSet.getString(2));
                        user.setPassword(resultSet.getString(3));
                        //添加到集合中
                        users.add(user);

                    }
                    //8.关资源
                    resultSet.close();
                    prepareStatement.close();
                    connection.close();
                    //把集合中的数据存储在作用域中
                    req.setAttribute("users",users);
                    //打开页面
                    req.getRequestDispatcher("/user.jsp").forward(req,resp);

                } catch (SQLException e) {
                    e.printStackTrace();
                }


            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        }

    }

